package com.situ.onlinebookstore.front.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.onlinebookstore.common.entity.*;
import com.situ.onlinebookstore.common.mapper.*;
import com.situ.onlinebookstore.common.util.MD5Util;
import com.situ.onlinebookstore.common.util.SnowflakeUtil;
import com.situ.onlinebookstore.front.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.List;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final OrderDetailMapper orderDetailMapper;
    private final CartMapper cartMapper;
    private final GoodsMapper goodsMapper;
    private final SnowflakeUtil snowflakeUtil;
    private final AddrMapper addrMapper;
    private final UserMapper userMapper;

    @Override
    @Transactional

    public int create(Order order) throws Exception {
        order.setId(new Long(snowflakeUtil.nextId()).toString());

        //校验商品 不能超买超卖
        //遍历所有的购物车
        order.getCarts().forEach((c) -> {
            //取出购物车中的数据
            Cart cart = cartMapper.selectById(c.getId());
            if (ObjectUtils.isEmpty(cart)) {
                throw new RuntimeException("无效购物车");
            }
            if (!cart.getUserId().equals(order.getUserId())) {
                throw new RuntimeException("无权操作购物车");
            }
            ///商品的库存的验证
            if (cart.getGoods().getCount() < cart.getCount()) {
                throw new RuntimeException("库存不足！");
            }
            //商品的状态
            if (cart.getGoods().getStatus().equals(1)) {
                throw new RuntimeException("商品已下架！");
            }
            //生成订单详情
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getId());
            orderDetail.setCount(cart.getCount());
            orderDetail.setPrice(cart.getGoods().getPrice());
            orderDetail.setGoodsId(cart.getGoodsId());

            //保存到数据库中
            orderDetailMapper.insert(orderDetail);
            //删除当前购物车
            cartMapper.delete(cart.getId());
        });
        //处理收货地址
        Addr addr = addrMapper.selectById(order.getAddrId());
        if (ObjectUtils.isEmpty(addr)) {
            throw new RuntimeException("无效的收货地址");
        }
        if (!addr.getUserId().equals(order.getUserId())) {
            throw new Exception("无权使用的收货地址");
        }
        order.setAddrDetail(
                addr.getProvince() +
                        addr.getCity() +
                        addr.getCounty() +
                        addr.getTown() +
                        addr.getDetail() + "--" +
                        addr.getContact() + "--" +
                        addr.getPhone()
        );
        //保存订单
        return orderMapper.insert(order);
    }

    @Override
    public int edit(Order order) throws Exception {
        return 0;
    }

    @Override
    public int remove(Order order) throws Exception {
        return 0;
    }

    @Override
    public Order getById(String id, Integer userId) throws Exception {
        //根据ID查询订单
        Order order = orderMapper.selectById(id);
        if (ObjectUtils.isEmpty(order)) {
            throw new Exception("无效的订单！");
        }
        if (!order.getUserId().equals(userId)) {
            throw new Exception("无权操作的订单！");
        }
        return order;
    }

    @Override
    public PageInfo searchForPage(Integer page, Integer limit, Order order) {
        PageHelper.startPage(page,limit);
        List list = orderMapper.select(order);
        return new PageInfo(list);
    }

    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE)  //数据一致性要求很高
    public int pay(String orderId, String payPassword, Integer userId) throws Exception {
        //1.获取订单信息
        Order order = orderMapper.selectById(orderId);
        if (!order.getStatus().equals(0)) {
            throw new Exception("请不要重复支付！");
        }
        //2.校验订单
        BigDecimal sum = new BigDecimal(0);
        for (OrderDetail orderDetail : order.getDetails()) {
            //商品的数量
            if (orderDetail.getCount() > orderDetail.getGoods().getCount()) {
                //库存不足
                throw new RuntimeException("库存不足");
            }
            //商品状态
            if (orderDetail.getGoods().getStatus() == 1) {
                //商品已下架
                throw new RuntimeException("商品已下架");
            }
            //扣库存
            Goods goods = orderDetail.getGoods();
            goods.setCount(goods.getCount() - orderDetail.getCount());
            goodsMapper.update(goods);
            //计算总价
            sum = sum.add(orderDetail.getGoods().getPrice().multiply(
                    new BigDecimal(orderDetail.getCount())));
        }
        //3。获取用户的信息
        User user = userMapper.selectById(userId);
        //4.校验用户的支付密码和余额
        if (ObjectUtils.isEmpty(user.getPayPassword())) {
            throw new Exception("未设置支付密码");
        }
        String md5Pwd = MD5Util.getDBMD5(payPassword,user.getSalt());
        if (!user.getPayPassword().equals(md5Pwd)){
            throw new Exception("支付密码错误");
        }
        if (user.getMoney().compareTo(sum) == -1){
            throw new Exception("余额不足");
        }
        //5.更新订单状态
        order.setStatus(1); //已支付
        order.setPayType(0); //全额支付
        orderMapper.update(order);
        //6.更新用户的余额
        user.setMoney(user.getMoney().subtract(sum));
        return userMapper.update(user);
    }
}
